package com.javasm.adminapi.common.utils;



import com.javasm.adminapi.common.exception.ExceptionEnum;
import com.javasm.adminapi.common.exception.JavasmException;
import io.jsonwebtoken.*;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.io.Encoders;
import io.jsonwebtoken.security.Keys;
import io.jsonwebtoken.security.SignatureException;

import javax.crypto.SecretKey;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {
    //generateKey()生成的加密字符串,服务器的密钥
    private static final String keyStr = "o5k6MDd1ljUTcxr+vL5LTUDE4KzEAS1uPnloA1Sy3hs=";
    //过期时间
    private static final Long uidExpTime = 1000L * 60 * 60 * 24 * 15;

    private static final Long emailExpTime = 1000L * 60 * 30;



    private static final String UID = "uid";

    public static final String Server_Token = "javasm_token";

    public static String generateUid(Integer uid) {
        return generateUid(uid.toString());
    }
    //加密
    public static String generateUid(String uid) {
        return baseGenerateToken(uid,uidExpTime);
    }

    public static String generateEmail(String email) {
        return baseGenerateToken(email,emailExpTime);
    }

    private static String baseGenerateToken(String str,Long expTime){
        //加密的数据，存放的集合
        Map<String, Object> map = new HashMap<>();
        map.put(UID, str);
        //过期时间
        //这个Token字符串什么时候生成的
        Date time = new Date();
        //这个Token 什么时候过期
        Date lastTime = new Date(time.getTime() + expTime);
        //生成一个key
        Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(keyStr));
        //使用key 对数据 进行加密
        return Jwts.builder()
                .setClaims(map)//加密的数据
                .setIssuedAt(time)// 标签签名，加密的时间
                .setExpiration(lastTime)//过期的时间
                .signWith(key)//指定签名key，密钥
                .compact();
    }

    //解密
    public static String parse(String token) {
        //生成一个key
        Key key = Keys.hmacShaKeyFor(Decoders.BASE64.decode(keyStr));
        String str = null;
        try {
            Jws<Claims> jws = Jwts.parserBuilder()
                    .setSigningKey(key)
                    .build()
                    .parseClaimsJws(token);
            //获取jws的body
            Claims body = jws.getBody();
            //获取value值
            str = body.get(UID, String.class);
        } catch (ExpiredJwtException e) {
            throw new JavasmException(ExceptionEnum.Token_Expired_Error);
        } catch (UnsupportedJwtException e) {
            throw new JavasmException(ExceptionEnum.Token_Unsupported_Error);
        } catch (SignatureException e) {
            throw new JavasmException(ExceptionEnum.Token_Signature_Error);
        } catch (Exception e) {
            throw new JavasmException(ExceptionEnum.Server_Error);
        }
        return str;
    }

    //生成密钥
    private static void generateKey() {
        //这个方法，是用来生成服务端密钥的
        //服务端的密钥不会随意改变，不是每次都重新生成
        //如果，改变服务端密钥，之前的所有Token字符串，会集体失效
        SecretKey key = Keys.secretKeyFor(SignatureAlgorithm.HS256);
        //生成 加密的字符串
        String encode = Encoders.BASE64.encode(key.getEncoded());
        System.out.println(encode);
    }

    public static void main(String[] args) {
        /*String token = generateUid(100);
        System.out.println(token);*/
        String token = "eyJhbGciOiJIUzI1NiJ9.eyJ1aWQiOiIxMDAiLCJpYXQiOjE3NTg1MDc1NDYsImV4cCI6MTc1OTgwMzU0Nn0.yb6c2mGmcrQUK8TEqchw3hEKfN2596YThJi3mBI48qA";
        String uid = parse(token);
        System.out.println(uid);
    }


}
